package com.magicode.screen.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppConfig;
import com.magicode.screen.AppContext;
import com.magicode.screen.MainApplication;
import com.magicode.screen.R;
import com.magicode.screen.api.ApiHttpClient;
import com.magicode.screen.api.remote.MgcApi;
import com.magicode.screen.base.BaseActivity;
import com.magicode.screen.bean.Constants;
import com.magicode.screen.bean.UserEntity;
import com.magicode.screen.bean.UsersAPI;
import com.magicode.screen.react.activity.MainTabReactActivity;
import com.magicode.screen.util.CyptoUtils;
import com.magicode.screen.util.TLog;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.tencent.connect.UserInfo;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.http.HttpConfig;

/**
 * 第三方登录
 *
 * @author kymjs (http://www.kymjs.com/)
 */
public class ThirdPartyLoginActivity extends BaseActivity  {

    public static final int REQUEST_CODE_INIT = 0;
    private static final String BUNDLE_KEY_REQUEST_CODE = "BUNDLE_KEY_REQUEST_CODE";
    protected static final String TAG = ThirdPartyLoginActivity.class.getSimpleName();


    private final int requestCode = REQUEST_CODE_INIT;
    private String mUserName;
    private String mPassword;
    /**QQ登录**/
    private Tencent mTencent;//qq主操作对象
    private UserInfo userInfo;
    /** 微博登录 */
    private AuthInfo mAuthInfo;  //授权认证所需要的信息
    private SsoHandler mSsoHandler;//SSO 授权认证实例
    private Oauth2AccessToken mAccessToken;//
    /** 微信登录 */
    private IWXAPI api;
    public static String  type;
    private  String openID;

    private ReactInstanceManager mReactInstanceManager = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(null!=type) {
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

            AppContext.getInstance().cleanLoginInfo();
            switch (type) {
                case "qq":
                    qqLogin();
                    break;
                case "weibo":
                    weiboLogin();
                    break;
                case "weixin":
                    weixinLogin();
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    public void initView() {
    //    handledefaultLogin();
    }

    @Override
    public void initData() {
        mTencent = Tencent.createInstance(AppConfig.APP_QQ_KEY,this.getApplicationContext());
    }

    @Override
    public void onClick(View v) {

    }

    private void handleLogin() {

//        if (!prepareForLogin()) {
//            return;
//        }
//        mUserName = mEtUserName.getText().toString();
//        mPassword = mEtPassword.getText().toString();

        showWaitDialog(R.string.progress_login);
        MgcApi.login(mUserName, mPassword, mHandler);
    }
    private void handledefaultLogin() {
       if(null!= AppContext.getInstance()) {
           String userId= AppContext.getInstance().getLoginUid();
           String loginName= AppContext.getInstance().getProperty("user.loginName");
           String password= CyptoUtils.decode("MagicodeApplication", AppContext.getInstance().getProperty("user.password"));
           if(null!=userId &&!"".equals(userId) && null!=loginName &&!"".equals(loginName) &&
                   null!=password &&!"".equals(password)){
               MgcApi.defaultLogin(loginName, password, mHandler);
           }
       }
    }
    private void handleRegist(){
        Intent data = new Intent();
        data.putExtra(BUNDLE_KEY_REQUEST_CODE, requestCode);
        setResult(RESULT_OK, data);
        this.sendBroadcast(new Intent(Constants.INTENT_ACTION_USER_CHANGE));
        finish();
//        Intent intent=new Intent(this,RegistActivity.class);  //注册
//        startActivity(intent);
        overridePendingTransition(R.anim.anim_right_get_into, R.anim.anim_left_sign_out);
    }


    private void handleForgetPassword(){
        Intent data = new Intent();
        data.putExtra(BUNDLE_KEY_REQUEST_CODE, requestCode);
        setResult(RESULT_OK, data);
        this.sendBroadcast(new Intent(Constants.INTENT_ACTION_USER_CHANGE));
        finish();
//        Intent intent=new Intent(this,ForgetPassActivity.class);  //忘记密码
//        startActivity(intent);
        overridePendingTransition(R.anim.anim_right_get_into, R.anim.anim_left_sign_out);
    }

    private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                AsyncHttpClient client = ApiHttpClient.getHttpClient();
                HttpContext httpContext = client.getHttpContext();
                CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
                if (cookies != null) {
                    String tmpcookies = "";
                    for (Cookie c : cookies.getCookies()) {
                        TLog.log(TAG, "cookie:" + c.getName() + " " + c.getValue());
                        tmpcookies += (c.getName() + "=" + c.getValue()) + ";";
                    }
                    TLog.log(TAG, "cookies:" + tmpcookies);
                    AppContext.getInstance().setProperty(AppConfig.CONF_COOKIE, tmpcookies);
                    ApiHttpClient.setCookie(ApiHttpClient.getCookie(AppContext.getInstance()));
                    HttpConfig.sCookie = tmpcookies;
                }
                ObjectMapper mapper = new ObjectMapper();
                UserEntity userEntity = mapper.readValue(arg2, UserEntity.class);

                if (userEntity.isOk()) {
                    // 保存登录信息
                    AppContext.getInstance().saveUserInfo(userEntity.getEntity());
                    sendEventForReact();
                    finish();
                } else {
                    AppContext.getInstance().cleanLoginInfo();
                    Toast.makeText(getBaseContext(),userEntity.getMessage(), Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {

                e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
            }
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                              Throwable arg3) {
            Toast.makeText(getBaseContext(),R.string.tip_login_error_for_network, Toast.LENGTH_LONG).show();
        }
    };

    private void sendEventForReact() {
        ReactNativeHost rnh = AppContext.getInstance().getReactNativeHost();
        if (null != rnh) {
            mReactInstanceManager = rnh.getReactInstanceManager();
        }
        WritableMap params = Arguments.createMap();
        params.putString("login", "true");
        sendEvent(mReactInstanceManager.getCurrentReactContext(), "thirdLogin", params);
    }
    private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }
    private void handleLoginSuccess() {
        Intent data = new Intent();
        data.putExtra(BUNDLE_KEY_REQUEST_CODE, requestCode);
        setResult(RESULT_OK, data);
        this.sendBroadcast(new Intent(Constants.INTENT_ACTION_USER_CHANGE));
        finish();
        Intent intent=new Intent(this,MainTabReactActivity.class);  //回到主页
        startActivity(intent);
        overridePendingTransition(R.anim.anim_right_get_into, R.anim.anim_left_sign_out);
    }

//    private boolean prepareForLogin() {
//        if (!TDevice.hasInternet()) {
//            AppContext.showToastShort(R.string.tip_no_internet);
//            return false;
//        }
//        String uName = mEtUserName.getText().toString();
//        if (StringUtils.isEmpty(uName)) {
//            AppContext.showToastShort(R.string.tip_please_input_username);
//            mEtUserName.requestFocus();
//            return false;
//        }
//        String pwd = mEtPassword.getText().toString();
//        if (StringUtils.isEmpty(pwd)) {
//            AppContext.showToastShort(R.string.tip_please_input_password);
//            mEtPassword.requestFocus();
//            return false;
//        }
//        return true;
//    }


    /**
     * QQ登陆前，先做退出操作
     */
    private void qqLogin() {
        if(mTencent.isSessionValid() == true){
            mTencent.logout(this);
        }
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", new loginListener());//授权
        }

    }

    /**
     * 微博登陆
     */
    private void weiboLogin() {

        mAuthInfo = new AuthInfo(ThirdPartyLoginActivity. this,
                AppConfig.APP_WB_KEY, AppConfig.REDIRECT_URL ,
                "all");
        mSsoHandler = new SsoHandler(ThirdPartyLoginActivity. this, mAuthInfo);
        mSsoHandler.authorize( new AuthListener());
    }

    /**
     * 微信登陆
     */
    private void weixinLogin() {

        api= WXAPIFactory.createWXAPI(this,AppConfig.APP_WX_KEY,false);
        boolean aa= api.registerApp(AppConfig.APP_WX_KEY);
        if(api==null)
        {
            api= WXAPIFactory.createWXAPI(this, AppConfig.APP_WX_KEY, false);
            api.registerApp(AppConfig.APP_WX_KEY);
        }
//        api.handleIntent()
        if (!api.isWXAppInstalled()) {
            //提醒用户没有按照微信
            Toast.makeText(this, "没有安装微信,请先安装微信!", Toast.LENGTH_SHORT).show();
            return;
        }

        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "none";
    //  req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
        finish();
    }

    class loginListener implements IUiListener {//qq授权登录监听器

        @Override
        public void onError(UiError arg0) {
            // TODO Auto-generated method stub
            finish();
        }

        /**
         * 返回json数据样例
         *
         * {"ret":0,"pay_token":"D3D678728DC580FBCDE15722B72E7365",
         * "pf":"desktop_m_qq-10000144-android-2002-",
         * "query_authority_cost":448,
         * "authority_cost":-136792089,
         * "openid":"015A22DED93BD15E0E6B0DDB3E59DE2D",
         * "expires_in":7776000,
         * "pfkey":"6068ea1c4a716d4141bca0ddb3df1bb9",
         * "msg":"",
         * "access_token":"A2455F491478233529D0106D2CE6EB45",
         * "login_cost":499}
         */
        @Override
        public void onComplete(Object value) {
            // TODO Auto-generated method stub

            System.out.println("有数据返回..");
            if (value == null) {
                return;
            }

            try {
                JSONObject jo = (JSONObject) value;

                int ret = jo.getInt("ret");

                System.out.println("json=" + String.valueOf(jo));

                if (ret == 0) {
                    Toast.makeText(ThirdPartyLoginActivity.this, "授权成功",
                            Toast.LENGTH_LONG).show();

                    openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                    userInfo = new UserInfo(ThirdPartyLoginActivity.this, mTencent.getQQToken());//获取用户信息
                    userInfo.getUserInfo(new userInfoListener());
                    finish();
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub
            //取消授权
            finish();
        }
    }

   class  userInfoListener implements IUiListener {//qq获取用户信息监听器

        @Override
        public void onError(UiError arg0) {
            // TODO Auto-generated method stub
            finish();
        }

        /**
         * 返回用户信息样例
         *
         * {"is_yellow_year_vip":"0","ret":0,
         * "figureurl_qq_1":"http:\/\/q.qlogo.cn\/qqapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/40",
         * "figureurl_qq_2":"http:\/\/q.qlogo.cn\/qqapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/100",
         * "nickname":"攀爬←蜗牛","yellow_vip_level":"0","is_lost":0,"msg":"",
         * "city":"黄冈","
         * figureurl_1":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/50",
         * "vip":"0","level":"0",
         * "figureurl_2":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/100",
         * "province":"湖北",
         * "is_yellow_vip":"0","gender":"男",
         * "figureurl":"http:\/\/qzapp.qlogo.cn\/qzapp\/1104732758\/015A22DED93BD15E0E6B0DDB3E59DE2D\/30"}
         */
        @Override
        public void onComplete(Object arg0) {
            // TODO Auto-generated method stub
            if(arg0 == null){
                return;
            }
            try {
                JSONObject jo = (JSONObject) arg0;
                int ret = jo.getInt("ret");
                System.out.println("json=" + String.valueOf(jo));
                if(ret==0) {
                    String userId=mTencent.getOpenId();
                    String nickName = jo.getString("nickname");
                    String sex ="";
                    if(null==jo.getString("gender") ||"男".equals(jo.getString("gender"))){
                        sex ="Male";
                    }else if("女".equals(jo.getString("gender"))){
                        sex="Female";
                    }
                    String province= jo.getString("province");
                    String city= jo.getString("city");
                    String headimgurl= jo.getString("figureurl_qq_2");
                    MgcApi.outerLogin(userId, nickName, sex,province,city,openID,headimgurl,mHandler);
                    Toast.makeText(ThirdPartyLoginActivity.this, "你好，" + nickName,
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }


        }

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub
            finish();
        }
    }

    /******************************** 微博回调 ***********************************************/
    /**
     * 微博认证授权回调类。 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用
     * {@link SsoHandler#authorizeCallBack} 后， 该回调才会被执行。 2. 非 SSO
     * 授权时，当授权结束后，该回调就会被执行。 当授权成功后，请保存该 access_token、expires_in、uid 等信息到
     * SharedPreferences 中。
     */
    public class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if ( mAccessToken.isSessionValid()) {
                Toast.makeText(ThirdPartyLoginActivity.this, "授权成功", Toast.LENGTH_LONG).show();
                //mAccessToken.getUid() ，获取到UID，作为身份的唯一标示
                UsersAPI mUsersAPI = new UsersAPI(ThirdPartyLoginActivity.this, AppConfig.APP_WB_KEY , mAccessToken );
                long uid = Long.parseLong(mAccessToken.getUid());
                mUsersAPI.show(uid, mListener); //获取用户基本信息
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                 String code = values.getString("code");
                Toast.makeText(ThirdPartyLoginActivity.this,code, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onWeiboException(WeiboException e) {

        }
    }
    //获取用户信息的回调
    private RequestListener mListener = new RequestListener() {//微博获取用户信息
        @Override
        public void onComplete(String response) {
            if (!TextUtils. isEmpty(response)) {
                // 调用 User#parse 将JSON串解析成User对象，所有的用户信息全部在这里面
                try {
                    JSONObject json = new JSONObject(response);
                    String openId=mTencent.getOpenId();
                    String userId = json.getString("id");
                    String nickName = json.getString("screen_name");
                    String name = json.getString("name");
                    String sex ="";
                    if("m".equals(json.getString("gender"))){
                        sex ="Male";
                    }else if("f".equals(json.getString("gender"))){
                        sex="Female";
                    }
                    String province= json.getString("province");
                    String city= json.getString("city");
                    String headimgurl= json.getString("avatar_large");//180*180     profile_image_url 50*50
                    MgcApi.outerLogin(userId, name, sex,province,city,null,headimgurl,mHandler);
                    Toast.makeText(ThirdPartyLoginActivity.this, "你好，" + nickName,
                            Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }

        @Override
        public void onWeiboException(WeiboException e) {

        }
    };

    /**
     * 授权回调有效(微博)
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult( int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

}
